package cn.cds.withyou.admin.ui.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.squareup.otto.Subscribe;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.cds.withyou.admin.Application;
import cn.cds.withyou.admin.R;
import cn.cds.withyou.admin.actions.ActionsCreator;
import cn.cds.withyou.admin.stores.GameStore;
import cn.cds.withyou.admin.ui.widget.CommonTitleBar;
import cn.cds.withyou.lib.model.GameDto;
import cn.ljs.android.buses.ActionBus;
import cn.ljs.android.buses.DataBus;
import cn.ljs.android.ui.BaseActivity;
import cn.ljs.android.util.AppUtils;
import cn.ljs.android.util.TUtil;

/**
 * <p> Description: </p>
 * <p/>
 * <p> Copyright: Copyright (c) 2016 </p>
 *
 * @author: Json.Lee
 * @Version: 1.0
 * @CreateTime: 8/5/2016 14:43
 */
public class GameAddedActivity extends BaseActivity {

    @Bind(R.id.title_et)
    EditText titleEt;
    @Bind(R.id.signup_start_time_et)
    EditText signupStartTimeEt;
    @Bind(R.id.signup_end_time_et)
    EditText signupEndTimeEt;
    @Bind(R.id.game_start_time_et)
    EditText gameStartTimeEt;
    @Bind(R.id.game_end_time_et)
    EditText gameEndTimeEt;
    @Bind(R.id.course_pic_et)
    EditText coursePicEt;
    @Bind(R.id.comment_et)
    EditText commentEt;
    @Bind(R.id.content_scroll)
    ScrollView contentScroll;


    private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
    private final static SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static {
        DATE_FORMAT.setTimeZone(TimeZone.getDefault());
        TIME_FORMAT.setTimeZone(TimeZone.getDefault());
        DATE_TIME_FORMAT.setTimeZone(TimeZone.getDefault());
    }

    private ActionsCreator mCreator;
    private ActionBus mActionBus;
    private DataBus mDataBus;
    private GameStore mStore;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_added);
        ButterKnife.bind(this);

        init();
    }

    private void init() {
        contentScroll.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AppUtils.hideKeyBoard(GameAddedActivity.this);
                return false;
            }
        });

        mCreator = ActionsCreator.get();
        mActionBus = Application.getInstance().getActionsBus();
        mDataBus = Application.getInstance().getDataBus();
        mStore = GameStore.get();

        mDataBus.register(this);
        mActionBus.register(mStore);
    }

    @Override
    protected void onDestroy() {
        mActionBus.unregister(mStore);
        mDataBus.unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void updateUI (GameStore.GameEvent event) {
        switch (event.code) {
            case GameStore.GameEvent.GAME_ADDED_SUCC:
                TUtil.shortToast("添加成功。");
                finish();
                break;
            case GameStore.GameEvent.GAME_ADDED_FAIL:
                TUtil.shortToast("添加失败，请重试。");
                break;
            default:
                return;
        }
    }

    @OnClick({R.id.add_btn, R.id.signup_start_time_et, R.id.signup_end_time_et, R.id.game_start_time_et, R.id.game_end_time_et})
    public void onClick(View v) {
        AppUtils.hideKeyBoard(this);
        switch (v.getId()) {
            case CommonTitleBar.LEFT_BUTTON_ID:
                finish();
                break;
            case R.id.add_btn:
                GameDto game = getParams();
                if (checkParams(game)) {
                    mCreator.requestGameAdded(game);
                }
                break;
            case R.id.signup_start_time_et:
                showDate(signupStartTimeEt);
                break;
            case R.id.signup_end_time_et:
                showDate(signupEndTimeEt);
                break;
            case R.id.game_start_time_et:
                showDate(gameStartTimeEt);
                break;
            case R.id.game_end_time_et:
                showDate(gameEndTimeEt);
                break;
            default:
                return;
        }
    }

    private void showDate(final TextView tv) {
        final Calendar current = Calendar.getInstance();
        if (!TextUtils.isEmpty(tv.getText().toString().trim())) {
            try {
                current.setTime(DATE_TIME_FORMAT.parse(tv.getText().toString().trim()));
            } catch (ParseException e) {
            }
        }
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                current.set(year, monthOfYear, dayOfMonth);
                showTime(tv, current);
            }
        }, current.get(Calendar.YEAR), current.get(Calendar.MONTH), current.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    private void showTime(final TextView tv, final Calendar current) {
        TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                current.set(Calendar.HOUR_OF_DAY, hourOfDay);
                current.set(Calendar.MINUTE, minute);
                current.set(Calendar.SECOND, 0);
                tv.setText(DATE_TIME_FORMAT.format(current.getTime()));
            }
        }, current.get(Calendar.HOUR_OF_DAY), current.get(Calendar.MINUTE), true);
        dialog.show();
    }

    private boolean checkParams(GameDto game) {
        if (TextUtils.isEmpty(game.getGameName())) {
            TUtil.shortToast("请输入比赛标题。");
            return false;
        }
        if (0 >= game.getSignupStartT()) {
            TUtil.shortToast("请选择报名开始时间。");
            return false;
        }
        if (0 >= game.getSignupEndT()) {
            TUtil.shortToast("请选择报名结束时间。");
            return false;
        }
        if (0 >= game.getGameStartT()) {
            TUtil.shortToast("请选择比赛开始时间。");
            return false;
        }
        if (0 >= game.getGameEndT()) {
            TUtil.shortToast("请选择比赛结束时间。");
            return false;
        }
        if (game.getSignupStartT() >= game.getSignupEndT()) {
            TUtil.shortToast("报名结束时间应大于开始时间。");
            return false;
        }
        if (game.getSignupEndT() >= game.getGameStartT()) {
            TUtil.shortToast("比赛开始时间应大于报名结束时间。");
            return false;
        }
        if (game.getGameEndT() <= game.getSignupStartT()) {
            TUtil.shortToast("比赛结束时间应大于开始时间。");
            return false;
        }
        if (TextUtils.isEmpty(game.getGamePic())) {
            TUtil.shortToast("请输入比赛图片链接。");
            return false;
        }
        if (TextUtils.isEmpty(game.getGameContent())) {
            TUtil.shortToast("请输入比赛介绍及章程。");
            return false;
        }
        return true;
    }

    private GameDto getParams() {
        GameDto dto = new GameDto();
        dto.setGameName(titleEt.getText().toString());
        if (!TextUtils.isEmpty(signupStartTimeEt.getText().toString().trim())) {
            try {
                Date date = DATE_TIME_FORMAT.parse(signupStartTimeEt.getText().toString().trim());
                dto.setSignupStartT(date.getTime());
            } catch (ParseException e) {
                dto.setSignupStartT(0);
            }
        }
        if (!TextUtils.isEmpty(signupEndTimeEt.getText().toString().trim())) {
            try {
                Date date = DATE_TIME_FORMAT.parse(signupEndTimeEt.getText().toString().trim());
                dto.setSignupEndT(date.getTime());
            } catch (ParseException e) {
                dto.setSignupEndT(0);
            }
        }
        if (!TextUtils.isEmpty(gameStartTimeEt.getText().toString().trim())) {
            try {
                Date date = DATE_TIME_FORMAT.parse(gameStartTimeEt.getText().toString().trim());
                dto.setGameStartT(date.getTime());
            } catch (ParseException e) {
                dto.setGameStartT(0);
            }
        }
        if (!TextUtils.isEmpty(gameEndTimeEt.getText().toString().trim())) {
            try {
                Date date = DATE_TIME_FORMAT.parse(gameEndTimeEt.getText().toString().trim());
                dto.setGameEndT(date.getTime());
            } catch (ParseException e) {
                dto.setGameEndT(0);
            }
        }
        dto.setGamePic(coursePicEt.getText().toString().trim());
        dto.setGameContent(commentEt.getText().toString().trim());
        return dto;
    }
}
